/**
 * 
 */
package com.cares.core.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @作者 Stone
 * @创建日期 2014-8-18 下午12:38:13
 * @版本 V1.0
 * @类说明
 */
public class SystemConfiguration {
	SystemConfiguration() {
	}

	static String systemConfiguration = "application.properties";
	
	private static Logger logger = LoggerFactory.getLogger(SystemConfiguration.class);

	static Properties initInfos;

	static {
		init();
	}

	private static void init() {
		/**
		 * 首先读取SystemConfig类包下的SystemConfig.properties文件
		 * 然后在读取当前classLoader下的SystemConfig.properties，如有重复的key则覆盖前面的值
		 */
		
		InputStream inputStream;
		
		try {
			ClassLoader cl = SystemConfiguration.class.getClassLoader();
			
			if(cl!=null) {
				inputStream = cl.getResourceAsStream(systemConfiguration);
			} else {
				inputStream = ClassLoader.getSystemResourceAsStream(systemConfiguration);
			}
			
			initInfos = new  Properties();
			initInfos.load(inputStream);
			inputStream.close();
			if (logger.isInfoEnabled()) {
				logger.info("Load " + systemConfiguration
						+ " from default classloader.");
			}
		} catch (IOException e) {
			if (logger.isInfoEnabled()) {
				logger.info("Can not find  " + systemConfiguration
						+ " in default classloader.");
			}
		}

	}

	public static String getPropertyValue(String key) {
		return getPropertyValue(key, "");
	}

	/**
	 * 如果自己添加系统以为的key value，则用此函数取得;
	 * 
	 * @param key
	 * @return
	 */
	public static String getPropertyValue(String key, String defaultValue) {
		return resolveValue(PropertiesUtils.getStringValue(key, initInfos,
				defaultValue));
	}

	/**
	 * 使用${}来表示属性文件中其他的key值
	 * 
	 * @param value
	 * @return
	 */
	static String resolveValue(String value) {
		if (StringUtil.isEmpty(value))
			return value;
		int prefixIndex = value.indexOf("${");
		if (prefixIndex < 0)
			return value;
		while (prefixIndex > -1) {
			int postfixIndex = value.indexOf("}", prefixIndex);
			if (postfixIndex < 0)
				throw new IllegalArgumentException("must have end sign } of ["
						+ value + "].");
			value = value.substring(0, prefixIndex)
					+ initInfos.getProperty(value.substring(prefixIndex + 2,
							postfixIndex)) + value.substring(postfixIndex + 1);
			prefixIndex = value.indexOf("${");
		}
		return value;
	}
}
